home *** CD-ROM | disk | FTP | other *** search
/ isnet Internet / Isnet Internet CD.iso / prog / hiz / 09 / 09.exe / adynware.exe / perl / lib / site / DBI.pm < prev    next >
Encoding:
Perl POD Document  |  1999-12-28  |  69.4 KB  |  2,166 lines

  1. require 5.003;
  2.  
  3. $DBI::VERSION = '0.89'; # ==> ALSO update the version in the pod text below!
  4.  
  5. =head1 NAME
  6.  
  7. DBI - Database independent interface for Perl
  8.  
  9. =head1 SYNOPSIS
  10.  
  11.   use DBI;
  12.  
  13.   @data_sources = DBI->data_sources($driver_name);
  14.  
  15.   $dbh = DBI->connect($data_source, $username, $auth);
  16.   $dbh = DBI->connect($data_source, $username, $auth, \%attr);
  17.  
  18.   $rc  = $dbh->disconnect;
  19.  
  20.   $rv  = $dbh->do($statement);
  21.   $rv  = $dbh->do($statement, \%attr);
  22.   $rv  = $dbh->do($statement, \%attr, @bind_values);
  23.  
  24.   $sth = $dbh->prepare($statement);
  25.   $sth = $dbh->prepare($statement, \%attr);
  26.  
  27.   $rc = $sth->bind_col($col_num, \$col_variable);
  28.   $rc = $sth->bind_columns(\%attr, @list_of_refs_to_vars_to_bind);
  29.  
  30.   $rv = $sth->bind_param($param_num, $bind_value);
  31.   $rv = $sth->bind_param($param_num, $bind_value, $bind_type);
  32.   $rv = $sth->bind_param($param_num, $bind_value, \%attr);
  33.  
  34.   $rv = $sth->execute;
  35.   $rv = $sth->execute(@bind_values);
  36.  
  37.   @row_ary  = $sth->fetchrow_array;
  38.   $ary_ref  = $sth->fetchrow_arrayref;
  39.   $hash_ref = $sth->fetchrow_hashref;
  40.  
  41.   $rc = $sth->finish;
  42.  
  43.   $rv = $sth->rows;
  44.  
  45.   $rc  = $dbh->commit;
  46.   $rc  = $dbh->rollback;
  47.  
  48.   $sql = $dbh->quote($string);
  49.  
  50.   $rc  = $h->err;
  51.   $str = $h->errstr;
  52.   $rv  = $h->state;
  53.  
  54. =head2 NOTE
  55.  
  56. This is the draft DBI specification that corresponds to the DBI version 0.89
  57. ($Date: 1997/07/25 11:17:49 $).
  58.  
  59.  * The DBI specification is currently evolving quite quickly so it is
  60.  * important to check that you have the latest copy. The RECENT CHANGES
  61.  * section below has a summary of user-visible changes and the F<Changes>
  62.  * file supplied with the DBI holds more detailed change information.
  63.  
  64.  * Note also that whenever the DBI changes the drivers take some time to
  65.  * catch up. Recent versions of the DBI have added many new features that
  66.  * may not yet be supported by the drivers you use. Talk to the authors of
  67.  * those drivers if you need the features.
  68.  
  69. Please also read the DBI FAQ which is installed as a DBI::FAQ module so
  70. you can use perldoc to read it by executing the C<perldoc DBI::FAQ> command.
  71.  
  72. =head2 RECENT CHANGES 
  73.  
  74. A brief summary of significant user-visible changes in recent versions
  75. (if a recent version isn't mentioned it simply means that there were no
  76. significant user-visible changes in that version).
  77.  
  78. =over 4 
  79.  
  80. =item DBI 0.86 - 16th July 1997
  81.  
  82. Added $h->{LongReadLen} and $h->{LongTruncOk} attributes for BLOBS.
  83. Added DBI_USER and DBI_PASS env vars. See L</connect> for usage.
  84. Added DBI->trace() to set global trace level (like per-handle $h->trace).
  85. PERL_DBI_DEBUG env var renamed DBI_TRACE (old name still works for now).
  86. Updated docs, including commit, rollback, AutoCommit and Transactions sections.
  87. Added bind_param method and execute(@bind_values) to docs.
  88.  
  89. =item DBI 0.85 - 25th June 1997
  90.  
  91. The 'new-style connect' (see below) now defaults to AutoCommit mode unless
  92. { AutoCommit => 0 } specified in connect attributes (see L</connect>).
  93. New DBI_DSN env var default for connect method (supersedes DBI_DRIVER).
  94. Documented the func method.
  95.  
  96. =item DBI 0.84 - 20th June 1997
  97.  
  98. Added $h->{PrintError} attribute which, if set true, causes all errors
  99. to trigger a warn().  New-style DBI->connect call now automatically
  100. sets PrintError=1 unless { PrintError => 0 } specified in the connect
  101. attributes (see L</connect>).  The old-style connect with a separate
  102. driver parameter is deprecated.  Renamed $h->debug to $h->trace() and
  103. added a trace filename arg.
  104.  
  105. =item DBI 0.83 - 11th June 1997
  106.  
  107. Added 'new-style' driver specification syntax to the DBI->connect
  108. data_source parameter: DBI->connect( 'dbi:driver:...', $user, $passwd);
  109. The DBI->data_sources method should return data_source names with the
  110. appropriate 'dbi:driver:' prefix.  DBI->connect will warn if \%attr is
  111. true but not a hash ref.  Added new fetchrow methods (fetchrow_array,
  112. fetchrow_arrayref and fetchrow_hashref):  Added the DBI FAQ from
  113. Alligator Descartes in module form for easy reading via "perldoc DBI::FAQ".
  114.  
  115. =item DBI 0.82 - 23rd May 1997
  116.  
  117. Added $h->{RaiseError} attribute which, if set true, causes all errors to
  118. trigger a die(). This makes it much easier to implement robust applications
  119. in terms of higher level eval { ... } blocks and rollbacks.
  120. Added DBI->data_sources($driver) method for implementation by drivers.
  121.  
  122. =back 
  123.  
  124. =cut
  125.  
  126.  
  127. {
  128. package DBI;
  129.  
  130. my $Revision = substr(q$Revision: 1.82 $, 10);
  131.  
  132.  
  133. use Carp;
  134. use DynaLoader ();
  135. use Exporter ();
  136.  
  137. @ISA = qw(Exporter DynaLoader);
  138.  
  139. @EXPORT_OK = qw();
  140. @EXPORT    = (); # populated by export_tags:
  141. %EXPORT_TAGS = (
  142.    sql_types => [ qw(SQL_CHAR SQL_NUMERIC SQL_DECIMAL SQL_INTEGER SQL_SMALLINT
  143.             SQL_FLOAT SQL_REAL SQL_DOUBLE SQL_VARCHAR) ],
  144.    utils     => [ qw(neat neat_list dump_results sql) ],
  145. );
  146. Exporter::export_ok_tags('sql_types', 'utils');
  147.  
  148. use strict;
  149.  
  150. $DBI::dbi_debug = $ENV{DBI_TRACE} || $ENV{PERL_DBI_DEBUG} || 0;
  151. carp "Loaded DBI.pm (debug $DBI::dbi_debug)\n" if $DBI::dbi_debug;
  152.  
  153. bootstrap DBI;
  154.  
  155. my $connect_via = "connect";
  156.  
  157. my $GATEWAY_INTERFACE = $ENV{GATEWAY_INTERFACE} || '';
  158. if (substr($GATEWAY_INTERFACE,0,8) eq 'CGI-Perl' and $INC{'Apache/DBI.pm'}) {
  159.     $connect_via = "Apache::DBI::connect";
  160.     carp "DBI connect via $INC{'Apache/DBI.pm'}\n" if $DBI::dbi_debug;
  161. }
  162.  
  163.  
  164. if ($DBI::dbi_debug) {
  165.     if ($DBI::dbi_debug =~ m/^\d/) {
  166.     DBI->trace($DBI::dbi_debug);
  167.     }
  168.     else {
  169.     DBI->trace(2, $DBI::dbi_debug);
  170.     }
  171. }
  172.  
  173. %DBI::installed_drh = ();  # maps driver names to installed driver handles
  174.  
  175.  
  176. tie $DBI::err,    'DBI::var', '*err';    # special case: referenced via IHA list
  177. tie $DBI::state,  'DBI::var', '"state';  # special case: referenced via IHA list
  178. tie $DBI::lasth,  'DBI::var', '!lasth';  # special case: return boolean
  179. tie $DBI::errstr, 'DBI::var', '&errstr'; # call &errstr in last used pkg
  180. tie $DBI::rows,   'DBI::var', '&rows';   # call &rows   in last used pkg
  181. sub DBI::var::TIESCALAR{ my $var = $_[1]; bless \$var, 'DBI::var'; }
  182. sub DBI::var::STORE    { Carp::croak "Can't modify \$DBI::${$_[0]} special variable" }
  183. sub DBI::var::DESTROY  { }
  184.  
  185.  
  186.  
  187. my $std = undef;
  188. my $keeperr = { O=>0x04 };
  189.  
  190. my @TieHash_IF = (    # Generic Tied Hash Interface
  191.     'STORE'   => $std,
  192.     'FETCH'   => $keeperr,
  193.     'FIRSTKEY'=> $keeperr,
  194.     'NEXTKEY' => $keeperr,
  195.     'EXISTS'  => $keeperr,
  196.     'CLEAR'   => $keeperr,
  197.     'DESTROY' => $keeperr,
  198. );
  199. my @Common_IF = (    # Interface functions common to all DBI classes
  200.     func    =>    {                O=>0x06    },
  201.     event   =>    { U =>[2,0,'$type, @args'],    O=>0x04 },
  202.     trace   =>    { U =>[1,2,'[$trace_level]'],    O=>0x04 },
  203.     debug   =>    { U =>[1,2,'[$debug_level]'],    O=>0x04 }, # old name for trace
  204.     private_data =>    { U =>[1,1],            O=>0x04 },
  205.     err     =>    $keeperr,
  206.     errstr  =>    $keeperr,
  207.     state   =>    { U =>[1,1], O=>0x04 },
  208. );
  209.  
  210. my %DBI_IF = (    # Define the DBI Interface:
  211.  
  212.     dr => {        # Database Driver Interface
  213.     'connect'  =>    { U =>[1,5,'[$db [,$user [,$passwd [,\%attr]]]]'] },
  214.     'disconnect_all'=>{ U =>[1,1] },
  215.     data_sources => { U =>[1,2] },
  216.     @Common_IF,
  217.     @TieHash_IF,
  218.     },
  219.     db => {        # Database Session Class Interface
  220.     commit     =>    { U =>[1,1] },
  221.     rollback   =>    { U =>[1,1] },
  222.     'do'       =>    { U =>[2,0,'$statement [, \%attribs [, @bind_params ] ]'] },
  223.     prepare    =>    { U =>[2,3,'$statement [, \%attribs]'] },
  224.     handler    =>    { U =>[2,2,'\&handler'] },
  225.     ping       =>    { U =>[1,1] },
  226.     disconnect =>    { U =>[1,1] },
  227.     tables     =>    { U =>[1,1] },
  228.     quote      =>    { U =>[2,2, '$str'] },
  229.     rows       =>    $keeperr,
  230.     @Common_IF,
  231.     @TieHash_IF,
  232.     },
  233.     st => {        # Statement Class Interface
  234.     bind_col   =>    { U =>[3,4,'$column, \\$var [, \%attribs]'] },
  235.     bind_columns =>    { U =>[3,0,'\%attribs, \\$var1 [, \\$var2, ...]'] },
  236.     bind_param =>    { U =>[3,4,'$parameter, $var [, \%attribs]'] },
  237.     bind_param_inout => { U =>[4,5,'$parameter, \\$var, $maxlen, [, \%attribs]'] },
  238.     execute    =>    { U =>[1,0,'[@args]'] },
  239.  
  240.     fetch          =>    undef, # alias for fetchrow_arrayref
  241.     fetchrow_arrayref =>    undef,
  242.     fetchrow_hashref  =>    undef,
  243.     fetchrow_array    =>    undef,
  244.     fetchrow         =>    undef, # old alias for fetchrow_array
  245.  
  246.     fetchall_arrayref =>    { U =>[1,1] },
  247.  
  248.     blob_read  =>    { U =>[4,5,'$field, $offset, $len [, \\$buf [, $bufoffset]]'] },
  249.     blob_copy_to_file => { U =>[3,3,'$field, $filename_or_handleref'] },
  250.     finish     =>     { U =>[1,1] },
  251.     rows       =>    $keeperr,
  252.     @Common_IF,
  253.     @TieHash_IF,
  254.     },
  255. );
  256.  
  257. my($class, $method);
  258. foreach $class (keys %DBI_IF){
  259.     my %pkgif = %{$DBI_IF{$class}};
  260.     foreach $method (keys %pkgif){
  261.     DBI->_install_method("DBI::${class}::$method", 'DBI.pm',
  262.             $pkgif{$method});
  263.     }
  264. }
  265.  
  266.  
  267.  
  268. END {
  269.     print STDERR "    DBI::END\n" if $DBI::dbi_debug >= 2;
  270.     $DBI::PERL_ENDING = $DBI::PERL_ENDING = 1;    # avoid typo warning
  271.     DBI->disconnect_all();
  272.     print STDERR "    DBI::END complete\n" if $DBI::dbi_debug >= 2;
  273. }
  274.  
  275.  
  276.  
  277.  
  278. sub connect {
  279.     my $class = shift;
  280.     my($dsn, $user, $pass, $attr, $driver) = @_;
  281.     my $dsn_driver;
  282.     my $dbh;
  283.  
  284.     ($driver, $attr) = ($attr, $driver) if $attr and !ref($attr);
  285.  
  286.     $dsn ||= $ENV{DBI_DSN} || $ENV{DBI_DBNAME} || '';
  287.     $user = $ENV{DBI_USER} unless defined $user;
  288.     $pass = $ENV{DBI_PASS} unless defined $pass;
  289.  
  290.     if ($DBI::dbi_debug) {
  291.     local $^W = 0;    # prevent 'Use of uninitialized value' warnings
  292.     Carp::carp "$class->connect($dsn, $user, $pass, $driver, $attr)\n"
  293.     }
  294.     die 'Usage: $class->connect([$dsn [,$user [,$passwd [, $driver [,\%attr]]]]])'
  295.         if ( ($driver and ref $driver) or ($attr and not ref $attr));
  296.  
  297.     $dsn_driver = $1 if $dsn =~ s/^DBI:(.*?)://i;
  298.  
  299.     $driver = $dsn_driver if $dsn_driver and !$driver;
  300.  
  301.     my $drh = $class->install_driver($driver)
  302.         or confess "$class->install_driver($driver) failed";
  303.     warn "$class->$connect_via using $driver driver $drh\n" if $DBI::dbi_debug;
  304.  
  305.     unless ($dbh = $drh->$connect_via($dsn, $user, $pass, $attr)) {
  306.     warn "$class->connect failed: ".($drh->errstr)."\n" if $DBI::dbi_debug;
  307.     return undef;
  308.     }
  309.     warn "$class->connect = $dbh\n" if $DBI::dbi_debug;
  310.  
  311.     if ($dsn_driver && !$driver) { # new-style connect so new default semantics
  312.     $dbh->{PrintError} = 1;
  313.     $dbh->{AutoCommit} = 1;
  314.     }
  315.     if (ref $attr) {
  316.     my $a;
  317.     foreach $a (qw(PrintError RaiseError AutoCommit)) {
  318.         $dbh->{$a} = $attr->{$a} if exists $attr->{$a};
  319.     }
  320.     }
  321.  
  322.     $dbh;
  323. }
  324.  
  325.  
  326. sub disconnect_all {
  327.     Carp::carp "DBI::disconnect_all @_\n" if $DBI::dbi_debug;
  328.     foreach(keys %DBI::installed_drh){
  329.     warn "DBI::disconnect_all for '$_'\n" if $DBI::dbi_debug;
  330.     my $drh = $DBI::installed_drh{$_};
  331.     next unless ref $drh;    # avoid problems on premature death
  332.     $drh->disconnect_all();
  333.     }
  334. }
  335.  
  336.  
  337. sub install_driver {
  338.     my $class = shift;
  339.     my($driver, $attribs) = @_;
  340.     my $drh;
  341.  
  342.     $driver ||= $ENV{DBI_DRIVER} || '';
  343.  
  344.     $driver = $1 if $driver =~ s/^DBI:(.*?)://i;
  345.  
  346.     Carp::croak "DBI->install_driver: DBD driver not specified.\n"
  347.     unless $driver;
  348.  
  349.     return $drh if $drh = $DBI::installed_drh{$driver};
  350.  
  351.     Carp::carp "$class->install_driver($driver)\n" if $DBI::dbi_debug;
  352.     Carp::croak 'usage DBI->install_driver($driver [, \%attribs])'
  353.     unless ($class eq 'DBI' and $driver and @_<=3);
  354.  
  355.     eval "package DBI::_firesafe; require DBD::$driver";
  356.     if ($@) {
  357.     my $advice = "";
  358.     $advice = "\nPerhaps DBD::$driver was statically linked into a new perl binary."
  359.          ."\nIn which case you need to use that new perl binary."
  360.         if $@ =~ /Can't find loadable object/;
  361.     confess "install_driver($driver) failed: $@$advice\n"
  362.     }
  363.     Carp::carp "DBI->install_driver($driver) loaded\n" if $DBI::dbi_debug;
  364.  
  365.     _setup_driver($driver);
  366.  
  367.     my $driver_class = "DBD::$driver";
  368.     $drh = eval { $driver_class->driver($attribs || {}) };
  369.     croak "$driver_class initialisation failed: $@"
  370.     unless $drh && ref $drh && !$@;
  371.  
  372.     $DBI::installed_drh{$driver} = $drh;
  373.     Carp::carp "DBI->install_driver($driver) = $drh\n" if $DBI::dbi_debug;
  374.     $drh;
  375. }
  376.  
  377. sub _setup_driver {
  378.     my $driver = shift;
  379.     my $type;
  380.     foreach $type (qw(dr db st)){
  381.     my $class = "DBD::${driver}::$type";
  382.     no strict 'refs';
  383.     push(@{"${class}::ISA"},     "DBD::_::$type");
  384.     push(@{"${class}_mem::ISA"}, "DBD::_mem::$type");
  385.     }
  386. }
  387.  
  388.  
  389. *internal = \&DBD::Switch::dr::driver;
  390.  
  391.  
  392. sub available_drivers {
  393.     my($quiet) = @_;
  394.     my(@drivers, $d, $f);
  395.     local(*DBI::DIR);
  396.     my(%seen_dir, %seen_dbd);
  397.     foreach $d (@INC){
  398.     chomp($d); # perl 5 beta 3 bug in #!./perl -Ilib from Test::Harness
  399.     next unless -d "$d/DBD";
  400.     next if $seen_dir{$d};
  401.     $seen_dir{$d} = 1;
  402.     opendir(DBI::DIR,"$d/DBD") || Carp::carp "opendir $d/DBD: $!\n";
  403.     foreach $f (sort readdir(DBI::DIR)){
  404.         next unless $f =~ s/\.pm$//;
  405.         if ($seen_dbd{$f}){
  406.         Carp::carp "DBD::$f in $d is hidden by DBD::$f in $seen_dbd{$f}\n"
  407.             unless $quiet;
  408.             } else {
  409.         push(@drivers, $f);
  410.         }
  411.         $seen_dbd{$f} = $d;
  412.     }
  413.     closedir(DBI::DIR);
  414.     }
  415.     @drivers;
  416. }
  417.  
  418. sub data_sources {
  419.     my($class, $driver) = @_;
  420.     my $drh = $class->install_driver($driver);
  421.     return $drh->data_sources;
  422. }
  423.  
  424. sub neat_list {
  425.     my($listref, $maxlen, $sep) = @_;
  426.     $maxlen = 0 unless defined $maxlen;    # 0 == use internal default
  427.     $sep = ", " unless defined $sep;
  428.     join($sep, map { neat($_,$maxlen) } @$listref);
  429. }
  430.  
  431.  
  432. sub dump_results {
  433.     my($sth, $maxlen, $lsep, $fsep) = @_;
  434.     return 0 unless $sth;
  435.     $maxlen ||= 35;
  436.     $lsep   ||= "\n";
  437.     my $rows = 0;
  438.     my $ref;
  439.     while($ref = $sth->fetch) {
  440.     print $lsep if $rows++ and $lsep;
  441.     print neat_list($ref,$maxlen,$fsep);
  442.     }
  443.     print "\n$rows rows".($DBI::err ? " ($DBI::err: $DBI::errstr)" : "")."\n";
  444.     $rows;
  445. }
  446.  
  447.  
  448. sub sql {        # a simple sql shell
  449.     my $prompt = "dbi> ";
  450.     my $dbh;
  451.     $| = 1;
  452.     if (@ARGV) {
  453.     warn "DBI Connecting to @ARGV\n";
  454.     $dbh = DBI->connect(@ARGV);
  455.     die "$DBI::errstr\n" unless $dbh;
  456.     }
  457.     while(1) {
  458.     print "$prompt ";
  459.     my $cmd = <>;
  460.     return unless $cmd;
  461.     chomp $cmd;
  462.     warn("Not connected yet.\n"),next unless $dbh;
  463.     my $sth = $dbh->prepare($cmd);
  464.     if ($sth) {
  465.         dump_results($sth);
  466.     }
  467.     else {
  468.         warn "$DBI::errstr\n";
  469.     }
  470.     }
  471. }
  472.  
  473.  
  474. sub connect_test_perf {
  475.     my($class, $dsn,$dbuser,$dbpass, $attr) = @_;
  476.     croak "connect_test_perf needs hash ref as fourth arg" unless ref $attr;
  477.     my $loops ||= $attr->{dbi_loops} || 5;
  478.     my $par   ||= $attr->{dbi_par}   || 1;    # parallelism
  479.     my $verb  ||= $attr->{dbi_verb}  || 1;
  480.     print "$dsn: testing $loops sets of $par connections:\n";
  481.     require Benchmark;
  482.     require FileHandle;
  483.     $| = 1;
  484.     my $t0 = new Benchmark;        # not currently used
  485.     my $drh = $class->install_driver($dsn) or die "Can't install $dsn driver\n";
  486.     my $t1 = new Benchmark;
  487.     my $loop;
  488.     for $loop (1..$loops) {
  489.     my @cons;
  490.     print "Connecting... " if $verb;
  491.     for (1..$par) {
  492.         print "$_ ";
  493.         push @cons, ($drh->connect($dsn,$dbuser,$dbpass)
  494.             or die "Can't connect # $_: $DBI::errstr\n");
  495.     }
  496.     print "\nDisconnecting...\n" if $verb;
  497.     for (@cons) {
  498.         $_->disconnect or warn "bad disconnect $DBI::errstr"
  499.     }
  500.     }
  501.     my $t2 = new Benchmark;
  502.     my $td = Benchmark::timediff($t2, $t1);
  503.     printf "Made %2d connections in %s\n\n", $loops*$par, Benchmark::timestr($td);
  504.     return $td;
  505. }
  506.  
  507.  
  508. sub MakeMakerAttribs {
  509.     ();
  510. }
  511.  
  512.  
  513.  
  514. sub _new_handle {
  515.     my($class, $parent, $attr, $imp_data) = @_;
  516.     $parent = '' unless $parent;
  517.  
  518.     confess 'Usage: DBI::_new_handle'
  519.     .'($class_name, parent_handle, \%attribs, $imp_data)'."\n"
  520.     .'got: ('.join(", ",$class, $parent, $attr, $imp_data).")\n"
  521.     unless(@_ == 4
  522.         and (!$parent or ref $parent)
  523.         and ref $attr eq 'HASH'
  524.         );
  525.  
  526.     my $imp_class = $attr->{ImplementorClass} or
  527.     croak "_new_handle($class): 'ImplementorClass' attribute not given";
  528.  
  529.     printf(STDERR "    New $class (for $imp_class, parent=$parent, id=%s)\n",
  530.         ($imp_data||''))
  531.     if ($DBI::dbi_debug >= 2);
  532.  
  533.     warn "_new_handle($class): "
  534.         ."invalid implementor class '$imp_class' given\n"
  535.         unless $imp_class =~ m/::(dr|db|st)$/;
  536.  
  537.     my(%hash, $i, $h);
  538.     $i = tie    %hash, $class, $attr;  # ref to inner hash (for driver)
  539.     $h = bless \%hash, $class;         # ref to outer hash (for application)
  540.     my @imp_data;
  541.     push(@imp_data, $imp_data) if defined $imp_data;
  542.     DBI::_setup_handle($h, $imp_class, $parent, @imp_data);
  543.  
  544.     warn "    New $class => $h (inner=$i) for $imp_class\n"
  545.     if ($DBI::dbi_debug >= 2);
  546.     return $h unless wantarray;
  547.     ($h, $i);
  548. }
  549. {   # implement minimum constructors for the tie's (could be moved to xs)
  550.     package DBI::dr; sub TIEHASH { bless $_[1] };
  551.     package DBI::db; sub TIEHASH { bless $_[1] };
  552.     package DBI::st; sub TIEHASH { bless $_[1] };
  553. }
  554.  
  555.  
  556.  
  557. sub _new_drh {    # called by DBD::<drivername>::driver()
  558.     my($class, $initial_attr, $imp_data) = @_;
  559.     my($h_state_store, $h_err_store, $h_errstr_store) = (undef, 0, '');
  560.     my $attr = {
  561.     'ImplementorClass' => $class,
  562.     'Handlers'    => [],
  563.     'State'        => \$h_state_store,  # Holder for DBI::state
  564.     'Err'        => \$h_err_store,    # Holder for DBI::err
  565.     'Errstr'    => \$h_errstr_store, # Holder for DBI::errstr
  566.     'Debug'     => 0,
  567.     %$initial_attr,
  568.     'Type'=>'dr',
  569.     };
  570.     _new_handle('DBI::dr', undef, $attr, $imp_data);
  571. }
  572.  
  573. sub _new_dbh {    # called by DBD::<drivername>::dr::connect()
  574.     my($drh, $initial_attr, $imp_data) = @_;
  575.     my($imp_class) = $drh->{ImplementorClass};
  576.     $imp_class =~ s/::dr$/::db/;
  577.     confess "new db($drh, $imp_class): not given an driver handle"
  578.         unless $drh->{Type} eq 'dr';
  579.     my $attr = {
  580.     'ImplementorClass' => $imp_class,
  581.     %$initial_attr,
  582.     'Type'   => 'db',
  583.     'Driver' => $drh,
  584.     };
  585.     _new_handle('DBI::db', $drh, $attr, $imp_data);
  586. }
  587.  
  588. sub _new_sth {    # called by DBD::<drivername>::db::prepare()
  589.     my($dbh, $initial_attr, $imp_data) = @_;
  590.     my($imp_class) = $dbh->{ImplementorClass};
  591.     $imp_class =~ s/::db$/::st/;
  592.     confess "new st($dbh, $imp_class): not given a database handle"
  593.     unless (ref $dbh eq 'DBI::db' and $dbh->{Type} eq 'db');
  594.     my $attr = {
  595.     'ImplementorClass' => $imp_class,
  596.     %$initial_attr,
  597.     'Type'     => 'st',
  598.     'Database' => $dbh,
  599.     };
  600.     _new_handle('DBI::st', $dbh, $attr, $imp_data);
  601. }
  602.  
  603. } # end of DBI package scope
  604.  
  605.  
  606.  
  607.  
  608. {   package DBD::Switch::dr;
  609.     DBI::_setup_driver('Switch');    # sets up @ISA
  610.     require Carp;
  611.  
  612.     $imp_data_size = 0;
  613.     $imp_data_size = 0;    # avoid typo warning
  614.     $err = 0;
  615.  
  616.     sub driver {
  617.     return $drh if $drh;    # a package global
  618.  
  619.     my $inner;
  620.     ($drh, $inner) = DBI::_new_drh('DBD::Switch::dr', {
  621.         'Name'    => 'Switch',
  622.         'Version' => $DBI::VERSION,
  623.         'Attribution' => sub { "DBI-$DBI::VERSION Switch by Tim Bunce" },
  624.         }, \$err);
  625.     Carp::confess("DBD::Switch init failed!") unless ($drh && $inner);
  626.     $DBD::Switch::dr::drh;
  627.     }
  628.  
  629.     sub FETCH {
  630.     my($drh, $key) = @_;
  631.     return DBI->trace if $key eq 'DebugDispatch';
  632.     return undef if $key eq 'DebugLog';    # not worth fetching, sorry
  633.     return $drh->DBD::_::dr::FETCH($key);
  634.     undef;
  635.     }
  636.     sub STORE {
  637.     my($drh, $key, $value) = @_;
  638.     if ($key eq 'DebugDispatch') {
  639.         DBI->trace($value);
  640.     } elsif ($key eq 'DebugLog') {
  641.         DBI->trace(-1, $value);
  642.     } else {
  643.         $drh->DBD::_::dr::STORE($key, $value);
  644.     }
  645.     }
  646. }
  647.  
  648.  
  649.  
  650.  
  651. {   package DBD::_::common; # ====== Common base class methods ======
  652.     use strict;
  653.  
  654.  
  655.     sub FIRSTKEY { undef }
  656.     sub NEXTKEY  { undef }
  657.     sub EXISTS   { defined($_[0]->FETCH($_[1])) } # to be sure
  658.     sub CLEAR    { Carp::carp "Can't CLEAR $_[0] (DBI)" }
  659. }
  660.  
  661.  
  662. {   package DBD::_::dr;  # ====== DRIVER ======
  663.     @ISA = qw(DBD::_::common);
  664.     use strict;
  665.  
  666.     sub connect { # normally overridden, but a handy default
  667.     my($drh, $dsn, $user, $auth)= @_;
  668.     my($this) = DBI::_new_dbh($drh, {
  669.         'Name' => $dsn,
  670.         'User' => $user,
  671.         });
  672.     $this;
  673.     }
  674.     sub disconnect_all {    # Driver must take responsibility for this
  675.     Carp::confess "Driver has not implemented the disconnect_all method.";
  676.     }
  677.     sub data_sources {
  678.     Carp::confess "Driver has not implemented the data_sources method.";
  679.     }
  680. }
  681.  
  682.  
  683. {   package DBD::_::db;  # ====== DATABASE ======
  684.     @ISA = qw(DBD::_::common);
  685.     use strict;
  686.  
  687.     sub quote {
  688.     my $self = shift;
  689.     my $str  = shift;
  690.     return "NULL" unless defined $str;
  691.     $str=~s/'/''/g;        # ISO SQL2
  692.     "'$str'";
  693.     }
  694.  
  695.     sub rows { -1 }
  696.  
  697.     sub do {
  698.     my($dbh, $statement, $attribs, @params) = @_;
  699.     my $sth = $dbh->prepare($statement, $attribs) or return undef;
  700.     $sth->execute(@params) or return undef;
  701.     my $rows = $sth->rows;
  702.     ($rows == 0) ? "0E0" : $rows;
  703.     }
  704.  
  705.     sub commit    {
  706.     Carp::carp "commit: not supported by $_[0]\n" if $DBI::dbi_debug;
  707.     undef;
  708.     }
  709.     sub rollback{
  710.     Carp::carp "rollback: not supported by $_[0]\n" if $DBI::dbi_debug;
  711.     undef;
  712.     }
  713.     sub ping        { 1 }        # we assume that all is well
  714.     sub disconnect  { undef }
  715. }
  716.  
  717.  
  718. {   package DBD::_::st;  # ====== STATEMENT ======
  719.     @ISA = qw(DBD::_::common);
  720.     use strict;
  721.  
  722.     sub finish  { undef }
  723.     sub rows    { -1 }
  724.  
  725.     sub fetchrow_hashref {
  726.     my $sth = shift;
  727.     my $row = $sth->fetch or return undef;
  728.     my %hash;
  729.     @hash{ @{ $sth->FETCH('NAME') } } = @$row;
  730.     return \%hash;
  731.     }
  732.  
  733.     sub fetchall_arrayref {
  734.     my $sth = shift;
  735.     my $via = shift || 'fetch';    # XXX not documented: may change
  736.     my @rows;
  737.     my $row;
  738.     if ($via eq 'fetch') {
  739.         while( $row = $sth->fetch ) {
  740.         push @rows, [ @$row ];
  741.         }
  742.     }
  743.     elsif ($via eq 'fetchhash') {
  744.         while( $row = $sth->fetchhash ) {
  745.         push @rows, $row;
  746.         }
  747.     }
  748.     else { Carp::croak "fetchall($via) invalid" }
  749.     return \@rows;
  750.     }
  751.  
  752.     sub blob_copy_to_file {    # returns length or undef on error
  753.     my($self, $field, $filename_or_handleref, $blocksize) = @_;
  754.     my $fh = $filename_or_handleref;
  755.     my($len, $buf) = (0, "");
  756.     $blocksize ||= 512;    # not too ambitious
  757.     local(*FH);
  758.     unless(ref $fh) {
  759.         open(FH, ">$fh") || return undef;
  760.         $fh = \*FH;
  761.     }
  762.     while(defined($self->blob_read($field, $len, $blocksize, \$buf))) {
  763.         print $fh $buf;
  764.         $len += length $buf;
  765.     }
  766.     close(FH);
  767.     $len;
  768.     }
  769.  
  770.     sub DESTROY  { Carp::confess "Driver has not implemented DESTROY for @_" }
  771. }
  772.  
  773. {   # See install_driver
  774.     { package DBD::_mem::dr; @ISA = qw(DBD::_mem::common);    }
  775.     { package DBD::_mem::db; @ISA = qw(DBD::_mem::common);    }
  776.     { package DBD::_mem::st; @ISA = qw(DBD::_mem::common);    }
  777. }
  778.  
  779. 1;
  780. __END__
  781.  
  782. =head1 DESCRIPTION
  783.  
  784. The Perl DBI is a database access Application Programming Interface
  785. (API) for the Perl Language.  The DBI defines a set of functions,
  786. variables and conventions that provide a consistent database interface
  787. independant of the actual database being used.
  788.  
  789. It is important to remember that the DBI is just an interface. A thin
  790. layer of 'glue' between an application and one or more Database Drivers.
  791. It is the drivers which do the real work. The DBI provides a standard
  792. interface and framework for the drivers to operate within.
  793.  
  794. This document is a I<work-in-progress>. Although it is incomplete it
  795. should be useful in getting started with the DBI.
  796.  
  797.  
  798. =head2 Architecture of a DBI Application
  799.  
  800.              |<- Scope of DBI ->|
  801.                   .-.   .--------------.   .-------------.
  802.   .-------.       | |---| XYZ Driver   |---| XYZ Engine  |
  803.   | Perl  |       |S|   `--------------'   `-------------'
  804.   | script|  |A|  |w|   .--------------.   .-------------.
  805.   | using |--|P|--|i|---|Oracle Driver |---|Oracle Engine|
  806.   | DBI   |  |I|  |t|   `--------------'   `-------------'
  807.   | API   |       |c|...
  808.   |methods|       |h|... Other drivers
  809.   `-------'       | |...
  810.                   `-'
  811.  
  812. The API is the Application Perl-script (or Programming) Interface.  The
  813. call interface and variables provided by DBI to perl scripts. The API
  814. is implemented by the DBI Perl extension.
  815.  
  816. The 'Switch' is the code that 'dispatches' the DBI method calls to the
  817. appropriate Driver for actual execution.  The Switch is also
  818. responsible for the dynamic loading of Drivers, error checking/handling
  819. and other duties. The DBI and Switch are generally synonymous.
  820.  
  821. The Drivers implement support for a given type of Engine (database).
  822. Drivers contain implementations of the DBI methods written using the
  823. private interface functions of the corresponding Engine.  Only authors
  824. of sophisticated/multi-database applications or generic library
  825. functions need be concerned with Drivers.
  826.  
  827. =head2 Notation and Conventions
  828.  
  829.   DBI    static 'top-level' class name
  830.   $dbh   Database handle object
  831.   $sth   Statement handle object
  832.   $drh   Driver handle object (rarely seen or used in applications)
  833.   $h     Any of the $??h handle types above
  834.   $rc    General Return Code  (boolean: true=ok, false=error)
  835.   $rv    General Return Value (typically an integer)
  836.   @ary   List of values returned from the database, typically a row of data
  837.   $rows  Number of rows processed by a function (if available, else -1)
  838.   $fh    A filehandle
  839.   undef  NULL values are represented by undefined values in perl
  840.  
  841. Note that Perl will automatically destroy database and statement objects
  842. if all references to them are deleted.
  843.  
  844. Handle object attributes are shown as:
  845.  
  846. C<  $h-E<gt>{attribute_name}>   (I<type>)
  847.  
  848. where I<type> indicates the type of the value of the attribute (if it's
  849. not a simple scalar):
  850.  
  851.   \$   reference to a scalar: $h->{attr}       or  $a = ${$h->{attr}}
  852.   \@   reference to a list:   $h->{attr}->[0]  or  @a = @{$h->{attr}}
  853.   \%   reference to a hash:   $h->{attr}->{a}  or  %a = %{$h->{attr}}
  854.  
  855.  
  856. =head2 General Interface Rules & Caveats
  857.  
  858. The DBI does not have a concept of a `current session'. Every session
  859. has a handle object (i.e., a $dbh) returned from the connect method and
  860. that handle object is used to invoke database related methods.
  861.  
  862. Most data is returned to the perl script as strings (null values are
  863. returned as undef).  This allows arbitrary precision numeric data to be
  864. handled without loss of accuracy.  Be aware that perl may not preserve
  865. the same accuracy when the string is used as a number.
  866.  
  867. Dates and times are returned as character strings in the native format
  868. of the corresponding Engine.  Time Zone effects are Engine/Driver
  869. dependent.
  870.  
  871. Perl supports binary data in perl strings and the DBI will pass binary
  872. data to and from the Driver without change. It is up to the Driver
  873. implementors to decide how they wish to handle such binary data.
  874.  
  875. Multiple SQL statements may not be combined in a single statement
  876. handle, e.g., a single $sth.
  877.  
  878. Non-sequential record reads are not supported in this version of the
  879. DBI. E.g., records can only be fetched in the order that the database
  880. returned them and once fetched they are forgotten.
  881.  
  882. Positioned updates and deletes are not directly supported by the DBI.
  883. See the description of the CursorName attribute for an alternative.
  884.  
  885. Individual Driver implementors are free to provide any private
  886. functions and/or handle attributes that they feel are useful.  Private
  887. functions can be invoked using the DBI C<func> method (which is
  888. currently not documented). Private attributes are accessed just like
  889. standard attributes.
  890.  
  891. Character sets: Most databases which understand character sets have a
  892. default global charset and text stored in the database is, or should
  893. be, stored in that charset (if it's not then that's the fault of either
  894. the database or the application that inserted the data). When text is
  895. fetched it should be (automatically) converted to the charset of the
  896. client (presumably based on the locale). If a driver needs to set a
  897. flag to get that behaviour then it should do so. It should not require
  898. the application to do that.
  899.  
  900.  
  901. =head2 Naming Conventions
  902.  
  903. The DBI package and all packages below it (DBI::*) are reserved for
  904. use by the DBI. Package names beginning with DBD:: are reserved for use
  905. by DBI database drivers.  All environment variables used by the DBI
  906. or DBD's begin with 'DBI_' or 'DBD_'.
  907.  
  908. The letter case used for attribute names is significant and plays an
  909. important part in the portability of DBI scripts.  The case of the
  910. attribute name is used to signify who defined the meaning of that name
  911. and its values.
  912.  
  913.   Case of name  Has a meaning defined by
  914.   ------------  ------------------------
  915.   UPPER_CASE    Standards, e.g.,  X/Open, SQL92 etc (portable)
  916.   MixedCase     DBI API (portable), underscores are not used.
  917.   lower_case    Driver or Engine specific (non-portable)
  918.  
  919. It is of the utmost importance that Driver developers only use
  920. lowercase attribute names when defining private attributes.
  921.  
  922.  
  923. =head2 Data Query Methods
  924.  
  925. The DBI allows an application to `prepare' a statement for later execution.
  926. A prepared statement is identified by a statement handle object, e.g., $sth.
  927.  
  928. Typical method call sequence for a select statement:
  929.  
  930.   connect,
  931.     prepare,
  932.       execute, fetch, fetch, ... finish,
  933.       execute, fetch, fetch, ... finish,
  934.       execute, fetch, fetch, ... finish.
  935.  
  936. Typical method call sequence for a non-select statement:
  937.  
  938.   connect,
  939.     prepare,
  940.       execute,
  941.       execute,
  942.       execute.
  943.  
  944.  
  945. =head2 Placeholders and Bind Values
  946.  
  947. Some drivers support Placeholders and Bind Values. These drivers allow
  948. a database statement to contain placeholders, sometimes called
  949. parameter markers, that indicate values that will be supplied later,
  950. before the prepared statement is executed.  For example, an application
  951. might use the following to insert a row of data into the SALES table:
  952.  
  953.   insert into sales (product_code, qty, price) values (?, ?, ?)
  954.  
  955. or the following, to select the description for a product:
  956.  
  957.   select product_description from products where product_code = ?
  958.  
  959. The C<?> characters are the placeholders.  The association of actual
  960. values with placeholders is known as binding and the values are
  961. referred to as bind values. Undefined values or C<undef> can be used
  962. to indicate null values.
  963.  
  964. Without using placeholders, the insert statement above would have to
  965. contain the literal values to be inserted and it would have to be
  966. re-prepared and re-executed for each row. With placeholders, the insert
  967. statement only needs to be prepared once. The bind values for each row
  968. can be given to the execute method each time it's called. By avoiding
  969. the need to re-prepare the statement for each row the application
  970. typically many times faster! Here's an example:
  971.  
  972.   my $sth = $dbh->prepare(q{
  973.     insert into sales (product_code, qty, price) values (?, ?, ?)
  974.   }) || die $dbh->errstr;
  975.   while(<>) {
  976.       chop;
  977.       my($product_code, $qty, $price) = split(/,/);
  978.       $sth->execute($product_code, $qty, $price) || die $dbh->errstr;
  979.   }
  980.   $dbh->commit || die $dbh->errstr;
  981.  
  982. See L</execute> and L</bind_param> for more details.
  983.  
  984. =head2 SQL - A Query Language
  985.  
  986. Most DBI drivers require applications to use a dialect of SQL (the
  987. Structured Query Language) to interact with the database engine.  These
  988. links may provide some useful information about SQL:
  989.  
  990.   http://www.jcc.com/sql_stnd.html
  991.   http://w3.one.net/~jhoffman/sqltut.htm
  992.   http://skpc10.rdg.ac.uk/misc/sqltut.htm
  993.  
  994. The DBI itself does not mandate or require any particular language to
  995. be used.  It is language independant. In ODBC terms it is always in
  996. pass-thru mode. The only requirement is that queries and other
  997. statements must be expressed as a single string of letters passed
  998. as the first argument to the L</prepare> method.
  999.  
  1000. =head1 THE DBI CLASS
  1001.  
  1002. =head2 DBI Class Methods
  1003.  
  1004. =over 4
  1005.  
  1006. =item B<connect>
  1007.  
  1008.   $dbh = DBI->connect($data_source, $username, $password);
  1009.   $dbh = DBI->connect($data_source, $username, $password, \%attr);
  1010.  
  1011. Establishes a database connection (session) to the requested data_source.
  1012. Returns a database handle object.
  1013.  
  1014. Multiple simultaneous connections to multiple databases through multiple
  1015. drivers can be made via the DBI. Simply make one connect call for each
  1016. and keep a copy of each returned database handle.
  1017.  
  1018. The $data_source value should begin with 'dbi:driver_name:'. That
  1019. prefix will be stripped off and the driver_name part is used to specify
  1020. the driver.  As a convenience, if the $data_source field is undefined
  1021. or empty the DBI will substitute the value of the environment variable
  1022. DBI_DSN if any.
  1023.  
  1024. If driver is not specified, the environment variable DBI_DRIVER is
  1025. used. If that variable is not set then the connect dies.
  1026.  
  1027. If $username or $password are I<undefined> (rather than empty) then the
  1028. DBI will substitute the values of the DBI_USER and DBI_PASS environment
  1029. variables respectively.  The use of the environment for these values is
  1030. not recommended for security reasons. The mechanism is only intended to
  1031. simplify testing.
  1032.  
  1033. DBI->connect automatically installs the driver if it has not been
  1034. installed yet. Driver installation I<always> returns a valid driver
  1035. handle or it I<dies> with an error message which includes the string
  1036. 'install_driver' and the underlying problem. So, DBI->connect will die
  1037. on a driver installation failure and will only return undef on a
  1038. connect failure, for which $DBI::errstr will hold the error.
  1039.  
  1040. The $data_source argument (with the 'dbi:...:' prefix removed) and the
  1041. $username and $password arguments are then passed to the driver for
  1042. processing. The DBI does not define I<any> interpretation for the
  1043. contents of these fields.  The driver is free to interpret the
  1044. data_source, username and password fields in any way and supply
  1045. whatever defaults are appropriate for the engine being accessed
  1046. (Oracle, for example, uses the ORACLE_SID and TWO_TASK env vars if no
  1047. data_source is specified).
  1048.  
  1049. The AutoCommit and PrintError attributes for each connection default to
  1050. default to I<on> (see L</AutoCommit> and L</PrintError> for more information).
  1051.  
  1052. The \%attr parameter can be used to alter the default settings of the
  1053. PrintError, RaiseError and AutoCommit attributes. For example:
  1054.  
  1055.   $dbh = DBI->connect($data_source, $user, $pass, {
  1056.     PrintError => 0,
  1057.     AutoCommit => 0
  1058.   });
  1059.  
  1060. These are currently the I<only> defined uses for the DBI->connect \%attr.
  1061.  
  1062. Portable applications should not assume that a single driver will be
  1063. able to support multiple simultaneous sessions.
  1064.  
  1065. Where possible each session ($dbh) is independent from the transactions
  1066. in other sessions. This is useful where you need to hold cursors open
  1067. across transactions, e.g., use one session for your long lifespan
  1068. cursors (typically read-only) and another for your short update
  1069. transactions.
  1070.  
  1071. For compatibility with old DBI scripts the driver can be specified by
  1072. passing its name as the fourth argument to connect (instead of \%attr):
  1073.  
  1074.   $dbh = DBI->connect($data_source, $user, $pass, $driver);
  1075.  
  1076. In this 'old-style' form of connect the $data_source should not start
  1077. with 'dbi:driver_name:' and, even if it does, the embedded driver_name
  1078. will be ignored. The $dbh->{AutoCommit} attribute is I<undefined>. The
  1079. $dbh->{PrintError} attribute is off. And the old DBI_DBNAME env var is
  1080. checked if DBI_DSN is not defined.
  1081.  
  1082. =item B<available_drivers>
  1083.  
  1084.   @ary = DBI->available_drivers;
  1085.   @ary = DBI->available_drivers($quiet);
  1086.  
  1087. Returns a list of all available drivers by searching for DBD::* modules
  1088. through the directories in @INC. By default a warning will be given if
  1089. some drivers are hidden by others of the same name in earlier
  1090. directories. Passing a true value for $quiet will inhibit the warning.
  1091.  
  1092.  
  1093. =item B<data_sources>
  1094.  
  1095.   @ary = DBI->data_sources($driver);
  1096.  
  1097. Returns a list of all data sources (databases) available via the named
  1098. driver. The driver will be loaded if not already. If $driver is empty
  1099. or undef then the value of the DBI_DRIVER environment variable will be
  1100. used.
  1101.  
  1102. Note that many drivers have no way of knowing what data sources might
  1103. be available for it and thus, typically, return an empty list.
  1104.  
  1105.  
  1106. =item B<trace>
  1107.  
  1108.   DBI->trace($trace_level)
  1109.   DBI->trace($trace_level, $trace_file)
  1110.  
  1111. DBI trace information can be enabled for all handles using this DBI
  1112. class method. To enable trace information for a specific handle use
  1113. the similar $h->trace method described elsewhere.
  1114.  
  1115. Use $trace_level 2 to see detailed call trace information including
  1116. parameters and return values.  The trace output is detailed and
  1117. typically I<very> useful.
  1118.  
  1119. Use $trace_level 0 to disable the trace.
  1120.  
  1121. If $trace_filename is specified then the file is opened in append
  1122. mode and I<all> trace output (including that from other handles)
  1123. is redirected to that file.
  1124.  
  1125. See also the $h->trace() method and L</DEBUGGING> for information
  1126. about the DBI_TRACE environment variable.
  1127.  
  1128.  
  1129. =back
  1130.  
  1131.  
  1132. =head2 DBI Utility Functions
  1133.  
  1134. =over 4
  1135.  
  1136. =item B<neat>
  1137.  
  1138.   $str = DBI::neat($value, $maxlen);
  1139.  
  1140. Return a string containing a neat (and tidy) representation of the
  1141. supplied value. Strings will be quoted and undefined (NULL) values
  1142. will be shown as C<undef>. Unprintable characters will be replaced by
  1143. dot (.) and the string will be truncated and terminated with '...'
  1144. if longer than $maxlen (0 or undef defaults to 400 characters).
  1145.  
  1146. =item B<neat_list>
  1147.  
  1148.   $str = DBI::neat_list(\@listref, $maxlen, $field_sep);
  1149.  
  1150. Calls DBI::neat on each element of the list and returns a string
  1151. containing the results joined with $field_sep. $field_sep defaults
  1152. to C<", ">.
  1153.  
  1154.  
  1155. =item B<dump_results>
  1156.  
  1157.   $rows = DBI::dump_results($sth, $maxlen, $lsep, $fsep, $fh);
  1158.  
  1159. Fetches all the rows from $sth, calls DBI::neat_list for each row and
  1160. prints the results to $fh (defaults to C<STDOUT>) separated by $lsep
  1161. (default C<"\n">). $fsep defaults to C<", "> and $maxlen defaults to 35.
  1162. This function is designed as a handy utility for prototyping and
  1163. testing queries.
  1164.  
  1165. =back
  1166.  
  1167.  
  1168. =head2 DBI Dynamic Attributes
  1169.  
  1170. These attributes are always associated with the last handle used.
  1171.  
  1172. Where an attribute is Equivalent to a method call, then refer to
  1173. the method call for all related documentation.
  1174.  
  1175. =over 4
  1176.  
  1177. =item B<$DBI::err>
  1178.  
  1179. Equivalent to $h->err.
  1180.  
  1181. =item B<$DBI::errstr>
  1182.  
  1183. Equivalent to $h->errstr.
  1184.  
  1185. =item B<$DBI::state>
  1186.  
  1187. Equivalent to $h->state.
  1188.  
  1189. =item B<$DBI::rows>
  1190.  
  1191. Equivalent to $h->rows.
  1192.  
  1193. =back
  1194.  
  1195.  
  1196. =head1 METHODS COMMON TO ALL HANDLES
  1197.  
  1198. =over 4
  1199.  
  1200. =item B<err>
  1201.  
  1202.   $rv = $h->err;
  1203.  
  1204. Returns the native database engine error code from the last driver
  1205. function called.
  1206.  
  1207. =item B<errstr>
  1208.  
  1209.   $str = $h->errstr;
  1210.  
  1211. Returns the native database engine error message from the last driver
  1212. function called.
  1213.  
  1214. =item B<state>
  1215.  
  1216.   $str = $h->state;
  1217.  
  1218. Returns an error code in the standard SQLSTATE five character format.
  1219. Note that the specific success code C<00000> is translated to C<0>
  1220. (false). If the driver does not support SQLSTATE then state will
  1221. return C<S1000> (General Error) for all errors.
  1222.  
  1223. =item B<trace>
  1224.  
  1225.   $h->trace($trace_level);
  1226.   $h->trace($trace_level, $trace_filename);
  1227.  
  1228. DBI trace information can be enabled for a specific handle (and any
  1229. future children of that handle) by setting the trace level using the
  1230. trace method.
  1231.  
  1232. Use $trace_level 2 to see detailed call trace information including
  1233. parameters and return values.  The trace output is detailed and
  1234. typically I<very> useful.
  1235.  
  1236. Use $trace_level 0 to disable the trace.
  1237.  
  1238. If $trace_filename is specified then the file is opened in append
  1239. mode and I<all> trace output (including that from other handles)
  1240. is redirected to that file.
  1241.  
  1242. See also the DBI->trace() method and L</DEBUGGING> for information
  1243. about the DBI_TRACE environment variable.
  1244.  
  1245.  
  1246. =item B<func>
  1247.  
  1248.   $h->func(@func_arguments, $func_name);
  1249.  
  1250. The func method can be used to call private non-standard and
  1251. non-portable methods implemented by the driver. Note that the function
  1252. name is given as the I<last> argument.
  1253.  
  1254. =back
  1255.  
  1256.  
  1257. =head1 ATTRIBUTES COMMON TO ALL HANDLES
  1258.  
  1259. These attributes are common to all types of DBI handles.
  1260.  
  1261. Some attributes are inherited by I<child> handles. That is, the value
  1262. of an inherited attribute in a newly created statement handle is the
  1263. same as the value in the parent database handle. Changes to attributes
  1264. in the new statement handle do not affect the parent database handle
  1265. and changes to the database handle do not affect I<existing> statement
  1266. handles, only future ones.
  1267.  
  1268. Attempting to set or get the value of an undefined attribute is fatal,
  1269. except for private driver specific attributes (which all have names
  1270. starting with a lowercase letter).
  1271.  
  1272. =over 4
  1273.  
  1274. =item B<Warn> (inherited)
  1275.  
  1276.   $h->{Warn}
  1277.  
  1278. Enables useful warnings for certain bad practices. Enabled by default. Some
  1279. emulation layers, especially those for perl4 interfaces, disable warnings.
  1280.  
  1281. =item B<CompatMode> (inherited)
  1282.  
  1283.   $h->{CompatMode}
  1284.  
  1285. Used by emulation layers (such as Oraperl) to enable compatible behaviour
  1286. in the underlying driver (e.g., DBD::Oracle) for this handle. Not normally
  1287. set by application code.
  1288.  
  1289. =item B<InactiveDestroy>
  1290.  
  1291.   $h->{InactiveDestroy}
  1292.  
  1293. This attribute can be used to disable the effect of destroying a handle
  1294. (which would normally close a prepared statement or disconnect from the
  1295. database etc). It is specifically designed for use in unix applications
  1296. which 'fork' child processes. Either the parent or the child process,
  1297. but not both, should set InactiveDestroy on all their handles.
  1298.  
  1299. =item B<PrintError> (inherited)
  1300.  
  1301.   $h->{PrintError}
  1302.  
  1303. This attribute can be used to force errors to generate warnings (using
  1304. warn) in addition to returning error codes in the normal way.  When set
  1305. on, any method which results in an error occuring ($DBI::err being set
  1306. true) will cause the DBI to effectively do warn("$DBI::errstr").  Note
  1307. that the contents of the warning are currently just $DBI::errstr but
  1308. that may change and should not be relied upon.
  1309.  
  1310. By default DBI->connect sets PrintError on (except for old-style connect
  1311. usage, see connect for more details).
  1312.  
  1313. If desired, the warnings can be caught and processed using a $SIG{__WARN__}
  1314. handler or modules like CGI::ErrorWrap.
  1315.  
  1316. =item B<RaiseError> (inherited)
  1317.  
  1318.   $h->{RaiseError}
  1319.  
  1320. This attribute can be used to force errors to raise exceptions rather
  1321. than simply return error codes in the normal way. It defaults to off.
  1322. When set on, any method which results in an error occuring ($DBI::err
  1323. being set true) will cause the DBI to effectively do croak("$DBI::errstr").
  1324.  
  1325. If PrintError is also on then the PrintError is done before the
  1326. RaiseError unless no __DIE__ handler has been defined, in which case
  1327. PrintError is skipped since the croak will print the message.
  1328.  
  1329. Note that the contents of $@ are currently just $DBI::errstr but that
  1330. may change and should not be relied upon.
  1331.  
  1332. =item B<ChopBlanks> (inherited)
  1333.  
  1334.   $h->{ChopBlanks}
  1335.  
  1336. This attribute can be used to control the trimming of trailing space
  1337. characters from fixed width char fields. No other field types are
  1338. affected.
  1339.  
  1340. The default is false (it is possible that that may change).
  1341. Applications that need specific behaviour should set the attribute as
  1342. needed. Emulation interfaces should set the attribute to match the
  1343. behaviour of the interface they are emulating.
  1344.  
  1345. Drivers are not required to support this attribute but any driver which
  1346. does not must arrange to return undef as the attribute value.
  1347.  
  1348. =item B<LongReadLen> (inherited)
  1349.  
  1350.   $h->{LongReadLen}
  1351.  
  1352. This attribute may be used to control the maximum length of 'long' (or
  1353. 'blob') fields which the driver will read from the database
  1354. automatically when it fetches each row of data.
  1355.  
  1356. The default is typically 80 bytes but may vary between drivers. Most
  1357. applications using long fields will set this value to slightly larger
  1358. than the longest long field value which will be fetched.
  1359.  
  1360. See L</LongTruncOk> about truncation behaviour.
  1361.  
  1362. =item B<LongTruncOk> (inherited)
  1363.  
  1364.   $h->{LongTruncOk}
  1365.  
  1366. This attribute may be used to control the effect of fetching a long
  1367. field value which has been truncated (typically because it's longer
  1368. than the value of the LongReadLen attribute).
  1369.  
  1370. By default LongTruncOk is false and fetching a truncated long value
  1371. will cause the fetch to fail. (Applications should always take care to
  1372. check for errors after a fetch loop in case a database error, such as a
  1373. divide by zero or long field truncation, caused the fetch to terminate
  1374. prematurely.)
  1375.  
  1376. =back
  1377.  
  1378.  
  1379. =head1 DBI DATABASE HANDLE OBJECTS
  1380.  
  1381. =head2 Database Handle Methods
  1382.  
  1383. =over 4
  1384.  
  1385. =item B<prepare>
  1386.  
  1387.   $sth = $dbh->prepare($statement)           || die $dbh->errstr;
  1388.   $sth = $dbh->prepare($statement, \%attr)   || die $dbh->errstr;
  1389.  
  1390. Prepare a single statement for execution by the database engine and
  1391. return a  reference to a statement handle object which can be used to
  1392. get attributes of the statement and invoke the L</execute> method.
  1393.  
  1394. Note that prepare should never execute a statement, even if it is not a
  1395. select statement, it only prepares it for execution. Having said that,
  1396. some drivers, notably Oracle, will execute data definition statements
  1397. such as create/drop table when they are prepared. In practice this is
  1398. rarely a problem.
  1399.  
  1400. Drivers for engines which don't have the concept of preparing a
  1401. statement will typically just store the statement in the returned
  1402. handle and process it when $sth->execute is called. Such drivers are
  1403. likely to be unable to give much useful information about the
  1404. statement, such as $sth->{NUM_OF_FIELDS}, until after $sth->execute
  1405. has been called. Portable applications should take this into account.
  1406.  
  1407.  
  1408. =item B<do>
  1409.  
  1410.   $rc  = $dbh->do($statement)           || die $dbh->errstr;
  1411.   $rc  = $dbh->do($statement, \%attr)   || die $dbh->errstr;
  1412.   $rv  = $dbh->do($statement, \%attr, @bind_values) || ...
  1413.  
  1414. Prepare and execute a statement. Returns the number of rows affected
  1415. (-1 if not known or not available) or undef on error.
  1416.  
  1417. This method is typically most useful for non-select statements which
  1418. either cannot be prepared in advance (due to a limitation in the
  1419. driver) or which do not need to be executed repeatedly.
  1420.  
  1421. The default do method is logically similar to:
  1422.  
  1423.   sub do {
  1424.       my($dbh, $statement, $attr, @bind_values) = @_;
  1425.       my $sth = $dbh->prepare($statement) or return undef;
  1426.       $sth->execute(@bind_values) or return undef;
  1427.       my $rows = $sth->rows;
  1428.       ($rows == 0) ? "0E0" : $rows;
  1429.   }
  1430.  
  1431. Example:
  1432.  
  1433.   my $rows_deleted = $dbh->do(q{
  1434.       delete from table
  1435.       where status = 'DONE'
  1436.   }) || die $dbh->errstr;
  1437.  
  1438. Using placeholders and C<@bind_values> with the C<do> method can be
  1439. useful because it avoids the need to correctly quote any variables
  1440. in the $statement.
  1441.  
  1442. =item B<commit>
  1443.  
  1444.   $rc  = $dbh->commit     || die $dbh->errstr;
  1445.  
  1446. Commit (make permanent) the most recent series of database changes
  1447. if the database supports transactions.
  1448.  
  1449. If the database supports transactions and AutoCommit is on then the
  1450. commit should issue a "commit ineffective with AutoCommit" warning.
  1451.  
  1452. See also L</Transactions>.
  1453.  
  1454. =item B<rollback>
  1455.  
  1456.   $rc  = $dbh->rollback   || die $dbh->errstr;
  1457.  
  1458. Roll-back (undo) the most recent series of uncommitted database
  1459. changes if the database supports transactions.
  1460.  
  1461. If the database supports transactions and AutoCommit is on then the
  1462. rollback should issue a "rollback ineffective with AutoCommit" warning.
  1463.  
  1464. See also L</Transactions>.
  1465.  
  1466.  
  1467. =item B<disconnect>
  1468.  
  1469.   $rc  = $dbh->disconnect   || warn $dbh->errstr;
  1470.  
  1471. Disconnects the database from the database handle. Typically only used
  1472. before exiting the program. The handle is of little use after disconnecting.
  1473.  
  1474. The transaction behaviour of disconnect is undefined.  Some database
  1475. systems (such as Oracle and Ingres) will automatically commit any
  1476. outstanding changes, but others (such as Informix) will rollback any
  1477. outstanding changes.  Applications should explicitly call commit or
  1478. rollback before calling disconnect.
  1479.  
  1480. The database is automatically disconnected (by the DESTROY method) if
  1481. still connected when there are no longer any references to the handle.
  1482. The DESTROY method for each driver should explicitly call rollback to
  1483. undo any uncommitted changes. This is I<vital> behaviour to ensure that
  1484. incomplete transactions don't get committed simply because Perl calls
  1485. DESTROY on every object before exiting.
  1486.  
  1487.  
  1488. =item B<ping>
  1489.  
  1490.   $rc = $dbh->ping;
  1491.  
  1492. Attempts to determine, in a reasonably efficient way, if the database
  1493. server is still running and the connection to it is still working.
  1494. The default implementation currently always returns true without
  1495. actually doing anything. Individual drivers should implement this
  1496. function in the most suitable manner for their database engine.
  1497.  
  1498. Very few applications would have any use for this method. See the
  1499. specialist Apache::DBI module for one example usage.
  1500.  
  1501.  
  1502. =item B<quote>
  1503.  
  1504.   $sql = $dbh->quote($string);
  1505.  
  1506. Quote a string literal for use in an SQL statement by I<escaping> any
  1507. special characters (such as quotation marks) contained within the
  1508. string and adding the required type of outer quotation marks.
  1509.  
  1510.   $sql = sprintf "select foo from bar where baz = %s",
  1511.                 $dbh->quote("Don't\n");
  1512.  
  1513. For most database types quote would return C<'Don''t'> (including the
  1514. outer quotation marks).
  1515.  
  1516. An undefined $string value will be returned as NULL (without quotation
  1517. marks).
  1518.  
  1519. =back
  1520.  
  1521.  
  1522. =head2 Database Handle Attributes
  1523.  
  1524. =over 4
  1525.  
  1526. =item B<AutoCommit>
  1527.  
  1528.   $dbh->{AutoCommit}     ($)
  1529.  
  1530. If true then database changes cannot be rolledback (undone).  If false
  1531. then database changes automatically occur within a 'transaction' which
  1532. must either be committed or rolled-back using the commit or rollback
  1533. methods.
  1534.  
  1535. Drivers should always default to AutoCommit mode. (An unfortunate
  1536. choice forced on the DBI by ODBC and JDBC conventions.)
  1537.  
  1538. Attempting to set AutoCommit to an unsupported value is a fatal error.
  1539. This is an important feature of the DBI. Applications which need
  1540. full transaction behaviour can set $dbh->{AutoCommit}=0 (or via
  1541. connect) without having to check the value was assigned okay.
  1542.  
  1543. For the purposes of this description we can divide databases into three
  1544. categories:
  1545.  
  1546.   Database which don't support transactions at all.
  1547.   Database in which a transaction is always active.
  1548.   Database in which a transaction must be explicitly started ('BEGIN WORK').
  1549.  
  1550. B<* Database which don't support transactions at all>
  1551.  
  1552. For these databases attempting to turn AutoCommit off is a fatal error.
  1553. Commit and rollback both issue warnings about being ineffective while
  1554. AutoCommit is in effect.
  1555.  
  1556. B<* Database in which a transaction is always active>
  1557.  
  1558. These are typically mainstream commercial relational databases with
  1559. 'ANSI standandard' transaction behaviour.
  1560.  
  1561. If AutoCommit is off then changes to the database won't have any
  1562. lasting effect unless L</commit> is called (but see also
  1563. L</disconnect>). If L</rollback> is called then any changes since the
  1564. last commit are undone.
  1565.  
  1566. If AutoCommit is on then the effect is the same as if the DBI were to
  1567. have called commit automatically after every successful database
  1568. operation. In other words, calling commit or rollback explicitly while
  1569. AutoCommit is on would be ineffective because the changes would
  1570. have already been commited.
  1571.  
  1572. Changing AutoCommit from off to on may issue a L</commit> in some drivers.
  1573.  
  1574. Changing AutoCommit from on to off should have no immediate effect.
  1575.  
  1576. For databases which don't support a specific auto-commit mode, the
  1577. driver has to commit each statement automatically using an explicit
  1578. COMMIT after it completes successfully (and roll it back using an
  1579. explicit ROLLBACK if it fails).  The error information reported to the
  1580. application will correspond to the statement which was executed, unless
  1581. it succeeded and the commit or rollback failed.
  1582.  
  1583. B<* Database in which a transaction must be explicitly started>
  1584.  
  1585. For these database the intention is to have them act like databases in
  1586. which a transaction is always active (as described above).
  1587.  
  1588. To do this the DBI driver will automatically begin a transaction when
  1589. AutoCommit is turned off (from the default on state) and will
  1590. automatically begin another transaction after a L</commit> or L</rollback>.
  1591.  
  1592. In this way, the application does not have to treat these databases as a
  1593. special case.
  1594.  
  1595. =back
  1596.  
  1597.  
  1598. =head1 DBI STATEMENT HANDLE OBJECTS
  1599.  
  1600. =head2 Statement Handle Methods
  1601.  
  1602. =over 4
  1603.  
  1604. =item B<bind_param>
  1605.  
  1606.   $rc = $sth->bind_param($param_num, $bind_value)  || die $sth->errstr;
  1607.   $rv = $sth->bind_param($param_num, $bind_value, \%attr)     || ...
  1608.   $rv = $sth->bind_param($param_num, $bind_value, $bind_type) || ...
  1609.  
  1610. The bind_param method can be used to I<bind> (assign/associate) a value
  1611. with a I<placeholder> embedded in the prepared statement. Placeholders
  1612. are indicated with question mark character (C<?>). For example:
  1613.  
  1614.   $dbh->{RaiseError} = 1;        # save having to check each method call
  1615.   $sth = $dbh->prepare("select name, age from people where name like ?");
  1616.   $sth->bind_param(1, "John%");  # placeholders are numbered from 1
  1617.   $sth->execute;
  1618.   DBI::dump_results($sth);
  1619.  
  1620. Note that the C<?> is not enclosed in quotation marks even when the
  1621. placeholder represents a string.  Some drivers also allow C<:1>, C<:2>
  1622. etc and C<:name> style placeholders in addition to C<?> but their use
  1623. is not portable.
  1624.  
  1625. Sadly, placeholders can only represent single scalar values, so this
  1626. statement, for example, won't work as expected for more than one value:
  1627.  
  1628.   "select name, age from people where name in (?)"    # wrong
  1629.  
  1630. The C<\%attr> parameter can be used to specify the data type the
  1631. placeholder should have. Typically the driver is only interested in
  1632. knowing if the placeholder should be bound as a number or a string.
  1633.  
  1634.   $sth->bind_param(1, $value, { TYPE => SQL_INTEGER });
  1635.  
  1636. As a short-cut for this common case, the data type can be passed
  1637. directly inplace of the attr hash reference. This example is
  1638. equivalent to the one above:
  1639.  
  1640.   $sth->bind_param(1, $value, SQL_INTEGER);
  1641.  
  1642. Perl only has string and number scalar data types. All database types
  1643. that aren't numbers are bound as strings and must be in a format the
  1644. database will understand.
  1645.  
  1646. Undefined values or C<undef> can be used to indicate null values.
  1647.  
  1648.  
  1649. =item B<execute>
  1650.  
  1651.   $rv = $sth->execute                || die $sth->errstr;
  1652.   $rv = $sth->execute(@bind_values)  || die $sth->errstr;
  1653.  
  1654. Perform whatever processing is necessary to execute the prepared
  1655. statement.  An undef is returned if an error occurs, a successful
  1656. execute always returns true (see below). It is always important to
  1657. check the return status of execute (and most other DBI methods).
  1658.  
  1659. For a non-select statement execute returns the number of rows affected
  1660. (if known). Zero rows is returned as "0E0" which Perl will treat
  1661. as 0 but will regard as true. If the number of rows affected is not
  1662. known then execute returns -1.
  1663.  
  1664. For select statements execute simply 'starts' the query within the
  1665. Engine. Use one of the fetch methods to retreive the data after
  1666. calling execute.  Note that the execute method does I<not> return the
  1667. number of rows that will be returned by the query (because most Engines
  1668. can't tell in advance).
  1669.  
  1670. If any arguments are given then execute will effectively call
  1671. L</bind_param> for each value before executing the statement.
  1672. Values bound in this way are treated as SQL_VARCHAR types.
  1673.  
  1674.  
  1675. =item B<fetchrow_arrayref>
  1676.  
  1677.   $ary_ref = $sth->fetchrow_arrayref;
  1678.   $ary_ref = $sth->fetch;    # alias
  1679.  
  1680. Fetches the next row of data and returns a reference to an array
  1681. holding the field values. If there are no more rows fetchrow_arrayref
  1682. returns undef.  Null values are returned as undef. This is the fastest
  1683. way to fetch data, particularly if used with $sth->bind_columns.
  1684.  
  1685. =item B<fetchrow_array>
  1686.  
  1687.  @ary = $sth->fetchrow_array;
  1688.  
  1689. An alternative to C<fetchrow_arrayref>. Fetches the next row of data
  1690. and returns it as an array holding the field values. If there are no
  1691. more rows fetchrow_array returns an empty list.  Null values are
  1692. returned as undef.
  1693.  
  1694. =item B<fetchrow_hashref>
  1695.  
  1696.  $hash_ref = $sth->fetchrow_hashref;
  1697.  
  1698. An alternative to C<fetchrow_arrayref>. Fetches the next row of data
  1699. and returns it as a reference to a hash containing field name and field
  1700. value pairs.  Null values are returned as undef.  If there are no more
  1701. rows fetchhash returns undef.
  1702.  
  1703. The keys of the hash are the same names returned by $sth->{NAME}. If
  1704. more than one field has the same name there will only be one entry in
  1705. the returned hash.
  1706.  
  1707. Because of the extra work fetchrow_hashref and perl have to perform it
  1708. is not as efficient as fetchrow_arrayref or fetchrow_array and is not
  1709. recommended where performance is very important. Currently a new hash
  1710. reference is returned for each row.  This is likely to change in the
  1711. future so don't rely on it.
  1712.  
  1713.  
  1714. =item B<fetchall_arrayref>
  1715.  
  1716.   $tbl_ary_ref = $sth->fetchall_arrayref;
  1717.  
  1718. The C<fetchall_arrayref> method can be used to fetch all the data to be
  1719. returned from a prepared statement. It returns a reference to an array
  1720. which contains one array reference per row (as returned by
  1721. C<fetchrow_arrayref>).
  1722.  
  1723. If there are no rows to return, fetchall_arrayref returns a reference to an
  1724. empty array.
  1725.  
  1726.  
  1727. =item B<finish>
  1728.  
  1729.   $rc  = $sth->finish;
  1730.  
  1731. Indicates that no more data will be fetched from this statement before
  1732. it is either prepared again or destroyed.  It is helpful to call this
  1733. method where appropriate in order to allow the server to free off any
  1734. internal resources (such as read locks) currently being held. It does
  1735. not affect the transaction status of the session in any way.
  1736.  
  1737.  
  1738. =item B<rows>
  1739.  
  1740.   $rv = $sth->rows;
  1741.  
  1742. Returns the number of rows affected by the last database altering
  1743. command, or -1 if not known or not available.
  1744.  
  1745. Generally you can only rely on a row count after a do() or non-select
  1746. execute().  Some drivers only offer a row count after executing some
  1747. specific operations (e.g., update and delete).
  1748.  
  1749. It is generally not possible to know how many rows will be returned from
  1750. an arbitrary select statement except by fetching and counting them all.
  1751. Also note that some drivers, such as DBD::Oracle, implement read-ahead
  1752. row caches for select statements which means that the row count may
  1753. appear to be incorrect while there are still more records to fetch.
  1754.  
  1755.  
  1756. =item B<bind_col>
  1757.  
  1758.   $rc = $sth->bind_col($column_number, \$var_to_bind);
  1759.   $rc = $sth->bind_col($column_number, \$var_to_bind, \%attr);
  1760.  
  1761. Binds a column (field) of a select statement to a perl variable.
  1762. Whenever a row is fetched from the database the corresponding perl
  1763. variable is automatically updated. There is no need to fetch and assign
  1764. the values manually. This makes using bound variables very efficient.
  1765. See bind_columns below for an example.  Note that column numbers count
  1766. up from 1.
  1767.  
  1768. The binding is performed at a very low level using perl aliasing so
  1769. there is no extra copying taking place. So long as the driver uses the
  1770. correct internal DBI call to get the array the fetch function returns,
  1771. it will automatically support column binding.
  1772.  
  1773. =item B<bind_columns>
  1774.  
  1775.   $rc = $sth->bind_columns(\%attr, @list_of_refs_to_vars_to_bind);
  1776.  
  1777. e.g.
  1778.  
  1779.   $sth->prepare(q{ select region, sales from sales_by_region }) or die ...;
  1780.   my($region, $sales);
  1781.   $rv = $sth->bind_columns(undef, \$region, \$sales);
  1782.   while($sth->fetch) {
  1783.       print "$region: $sales\n";
  1784.   }
  1785.  
  1786. Calls bind_col for each column of the select statement. bind_columns will
  1787. croak if the number of references does not match the number of fields.
  1788.  
  1789. =back
  1790.  
  1791.  
  1792. =head2 Statement Handle Attributes
  1793.  
  1794. Note that some drivers cannot provide valid values for some or all of
  1795. these attributes until after $sth->execute has been called.
  1796.  
  1797. =over 4
  1798.  
  1799. =item B<NUM_OF_FIELDS>
  1800.  
  1801.   $sth->{NUM_OF_FIELDS}  ($)
  1802.  
  1803. Number of fields (columns) the prepared statement will return. Non-select
  1804. statements will have NUM_OF_FIELDS == 0.
  1805.  
  1806.  
  1807. =item B<NUM_OF_PARAMS>
  1808.  
  1809.   $sth->{NUM_OF_PARAMS}  ($)
  1810.  
  1811. The number of parameters (placeholders) in the prepared statement.
  1812. See SUBSTITUTION VARIABLES below for more details.
  1813.  
  1814.  
  1815. =item B<NAME>
  1816.  
  1817.   $sth->{NAME}           (\@)
  1818.  
  1819. Returns a I<reference> to an array of field names for each column. The
  1820. names may contain spaces but should not be truncated or have any
  1821. trailing space.
  1822.  
  1823.   print "First column name: $sth->{NAME}->[0]\n";
  1824.  
  1825.  
  1826. =item B<NULLABLE>
  1827.  
  1828.   $sth->{NULLABLE}       (\@)
  1829.  
  1830. Returns a I<reference> to an array indicating the possibility of each
  1831. column returning a null.
  1832.  
  1833.   print "First column may return NULL\n" if $sth->{NULLABLE}->[0];
  1834.  
  1835.  
  1836. =item B<CursorName>
  1837.  
  1838.   $sth->{CursorName}     ($)
  1839.  
  1840. Returns the name of the cursor associated with the statement handle if
  1841. available. If not available or the database driver does not support the
  1842. C<"where current of ..."> SQL syntax then it returns undef.
  1843.  
  1844.  
  1845. =back
  1846.  
  1847.  
  1848. =head1 TRANSACTIONS
  1849.  
  1850. Transactions are a fundamental part of any quality database system. They
  1851. protect against errors and database corruption by ensuring that changes
  1852. to the database take place in atomic (indivisible, all-or-nothing) units.
  1853.  
  1854. See L</AutoCommit> for details of using AutoCommit with various types of
  1855. database.
  1856.  
  1857. =head2 Robust Applications
  1858.  
  1859. This section applies to databases which support transactions and where
  1860. AutoCommit is off.
  1861.  
  1862. The recommended way to implement robust transactions in Perl
  1863. applications is to make use of S<C<eval { ... }>> (which is very fast,
  1864. unlike S<C<eval "...">>).
  1865.  
  1866.   eval {
  1867.       foo(...)
  1868.   };
  1869.   if ($@) {
  1870.       $dbh->rollback;
  1871.   }
  1872.   else {
  1873.       $dbh->commit;
  1874.   }
  1875.  
  1876. The code in foo(), or any other code executed from within the curly braces,
  1877. can be implemented in this way:
  1878.  
  1879.   $h->method(@args) || die $h->errstr
  1880.  
  1881. or the $h->{RaiseError} attribute can be set on, in which case the DBI
  1882. will automatically croak() on error so you don't have to test the
  1883. return value of each method call. See L</RaiseError> for more details.
  1884.  
  1885. A major advantage of the eval approach is that the transaction will be
  1886. properly rolled back if I<any> code in the inner application croaks or
  1887. dies for any reason.
  1888.  
  1889.  
  1890. =head1 SIMPLE EXAMPLE
  1891.  
  1892.   my $dbh = DBI->connect("dbi:Oracle:$data_source", $user, $password)
  1893.       || die "Can't connect to $data_source: $DBI::errstr";
  1894.  
  1895.   my $sth = $dbh->prepare( q{
  1896.           SELECT name, phone
  1897.           FROM mytelbook
  1898.   }) || die "Can't prepare statement: $DBI::errstr";
  1899.  
  1900.   my $rc = $sth->execute
  1901.       || die "Can't execute statement: $DBI::errstr";
  1902.  
  1903.   print "Query will return $sth->{NUM_FIELDS} fields.\n\n";
  1904.  
  1905.   print "$sth->{NAME}->[0]: $sth->{NAME}->[1]\n";
  1906.   while (($name, $phone) = $sth->fetchrow_array) {
  1907.       print "$name: $phone\n";
  1908.   }
  1909.   warn $DBI::errstr if $DBI::err;
  1910.  
  1911.   $sth->finish;
  1912.  
  1913.  
  1914. =head1 DEBUGGING
  1915.  
  1916. In addition to the L</trace> method you can enable the same trace
  1917. information by setting the DBI_TRACE environment variable before
  1918. starting perl.
  1919.  
  1920. On unix-like systems using a bourne-like shell you can do this easily
  1921. for a single command:
  1922.  
  1923.   DBI_TRACE=2 perl your_test_script.pl
  1924.  
  1925. If DBI_TRACE is set to a non-numeric value then it is assumed to
  1926. be a file name and the trace level will be set to 2 with all trace
  1927. output will be appended to that file.
  1928.  
  1929. See also the L</trace> method.
  1930.  
  1931.  
  1932. =head1 WARNINGS
  1933.  
  1934. The DBI is I<alpha> software. It is I<only> 'alpha' because the
  1935. interface (api) is not finalised. The alpha status does not reflect
  1936. code quality.
  1937.  
  1938. =head1 SEE ALSO
  1939.  
  1940. =head2 Database Documentation
  1941.  
  1942. SQL Language Reference Manual.
  1943.  
  1944. =head2 Books and Journals
  1945.  
  1946.  Programming Perl 2nd Ed. by Larry Wall, Tom Christiansen & Randal Schwartz.
  1947.  Learning Perl by Randal Schwartz.
  1948.  
  1949.  Dr Dobb's Journal, November 1996.
  1950.  The Perl Journal, April 1997.
  1951.  
  1952. =head2 Manual Pages
  1953.  
  1954. L<perl(1)>, L<perlmod(1)>, L<perlbook(1)>
  1955.  
  1956. =head2 Mailing List
  1957.  
  1958. The dbi-users mailing list is the primary means of communication among
  1959. uses of the DBI and its related modules. Subscribe and unsubscribe via:
  1960.  
  1961.  http://www.fugue.com/dbi
  1962.  
  1963. Mailing list archives are held at:
  1964.  
  1965.  http://www.rosat.mpe-garching.mpg.de/mailing-lists/PerlDB-Interest/
  1966.  http://www.coe.missouri.edu/~faq/lists/dbi.html
  1967.  
  1968. =head2 Assorted Related WWW Links
  1969.  
  1970. The DBI 'Home Page' (not maintained by me):
  1971.  
  1972.  http://www.hermetica.com/technologia/DBI
  1973.  
  1974. Other related links:
  1975.  
  1976.  http://www-ccs.cs.umass.edu/db.html
  1977.  http://www.odmg.org/odmg93/updates_dbarry.html
  1978.  http://www.jcc.com/sql_stnd.html
  1979.  ftp://alpha.gnu.ai.mit.edu/gnu/gnusql-0.7b3.tar.gz
  1980.  
  1981. =head2 FAQ
  1982.  
  1983. Please also read the DBI FAQ which is installed as a DBI::FAQ module so
  1984. you can use perldoc to read it by executing the C<perldoc DBI::FAQ> command.
  1985.  
  1986. =head1 AUTHORS
  1987.  
  1988. DBI by Tim Bunce.  This pod text by Tim Bunce, J. Douglas Dunlop,
  1989. Jonathan Leffler and others.  Perl by Larry Wall and the
  1990. perl5-porters.
  1991.  
  1992. =head1 COPYRIGHT
  1993.  
  1994. The DBI module is Copyright (c) 1995,1996,1997 Tim Bunce. England.
  1995. The DBI module is free software; you can redistribute it and/or
  1996. modify it under the same terms as Perl itself.
  1997.  
  1998. This document is Copyright (c) 1997 by Tim Bunce. All rights reserved.
  1999. Permission to distribute this document, in full or part, via email,
  2000. usenet or ftp/http archives or printed copy is granted providing that
  2001. no charges are involved, reasonable attempt is made to use the most
  2002. current version, and all credits and copyright notices are retained.
  2003. Requests for other distribution rights, including incorporation in
  2004. commercial products, such as books, magazine articles, or CD-ROMs
  2005. should be made to Tim.Bunce@ig.co.uk (please I<don't> use this mail
  2006. address for other DBI related mail - use the dbi-users mailing list).
  2007.  
  2008. =head1 ACKNOWLEDGEMENTS
  2009.  
  2010. I would like to acknowledge the valuable contributions of the many
  2011. people I have worked with on the DBI project, especially in the early
  2012. years (1992-1994): Kevin Stock, Buzz Moschetti, Kurt Andersen, Ted Lemon,
  2013. William Hails, Garth Kennedy, Michael Peppler, Neil S. Briscoe,
  2014. David J. Hughes, Jeff Stander, Forrest D Whitcher, Larry Wall, Jeff Fried,
  2015. Roy Johnson, Paul Hudson, Georg Rehfeld, Steve Sizemore, Ron Pool,
  2016. Jon Meek, Tom Christiansen, Steve Baumgarten, Randal Schwartz,
  2017. and a whole lot more.
  2018.  
  2019. =head1 SUPPORT / WARRANTY
  2020.  
  2021. The DBI is free software. IT COMES WITHOUT WARRANTY OF ANY KIND.
  2022.  
  2023. Commercial support agreements for Perl and the DBI, DBD::Oracle and
  2024. Oraperl modules can be arranged via The Perl Clinic. See
  2025. http://www.perl.co.uk/tpc for more details.
  2026.  
  2027. =head1 OUTSTANDING ISSUES TO DO
  2028.  
  2029.     data types (ISO type numbers and type name conversions)
  2030.     error handling
  2031.     data dictionary methods
  2032.     test harness support methods
  2033.     portability
  2034.     blob_read
  2035.     etc
  2036.  
  2037. =head1 FREQUENTLY ASKED QUESTIONS
  2038.  
  2039. See the DBI FAQ for a more comprehensive list of FAQs. Use the
  2040. C<perldoc DBI::FAQ> command to read it.
  2041.  
  2042. =head2 Why doesn't my CGI script work right?
  2043.  
  2044. Read the information in the references below.  Please do I<not> post
  2045. CGI related questions to the dbi-users mailing list (or to me).
  2046.  
  2047.  http://www.perl.com/perl/faq/idiots-guide.html
  2048.  http://www3.pair.com/webthing/docs/cgi/faqs/cgifaq.shtml
  2049.  http://www.perl.com/perl/faq/perl-cgi-faq.html
  2050.  http://www-genome.wi.mit.edu/WWW/faqs/www-security-faq.html
  2051.  http://www.boutell.com/faq/
  2052.  http://www.perl.com/perl/faq/
  2053.  
  2054. General problems and good ideas:
  2055.  
  2056.  Use the CGI::ErrorWrap module.
  2057.  Remember that many env vars won't be set for CGI scripts
  2058.  
  2059. =head2 How can I maintain a WWW connection to a database?
  2060.  
  2061. For information on the Apache httpd server and the mod_perl module see
  2062. http://www.osf.org/~dougm/apache
  2063.  
  2064. =head2 A driver build fails because it can't find DBIXS.h
  2065.  
  2066. The installed location of the DBIXS.h file changed with 0.77 (it was
  2067. being installed into the 'wrong' directory but that's where driver
  2068. developers came to expect it to be). The first thing to do is check to
  2069. see if you have the latest version of your driver. Driver authors will
  2070. be releasing new versions which use the new location. If you have the
  2071. latest then ask for a new release. You can edit the Makefile.PL file
  2072. yourself. Change the part which reads C<"-I.../DBI"> so it reads
  2073. C<"-I.../auto/DBI"> (where ... is a string of non-space characters).
  2074.  
  2075. =head2 Has the DBI and DBD::Foo been ported to NT / Win32?
  2076.  
  2077. The latest version of the DBI and, at least, the DBD::Oracle module
  2078. will build - without changes - on NT/Win32 I<if> your are using the
  2079. standard Perl 5.004 and I<not> the ActiveWare port.
  2080.  
  2081. Jeffrey Urlwin <jurlwin@access.digex.net> (or <jurlwin@hq.caci.com>) is
  2082. helping me with the port (actually he's doing it and I'm integrating
  2083. the changes :-).
  2084.  
  2085. =head2 What about ODBC?
  2086.  
  2087. See the statement and following notes in the DBI README file.
  2088.  
  2089.  
  2090. =head1 KNOWN DRIVER MODULES
  2091.  
  2092. =over 4
  2093.  
  2094. =item Oracle - DBD::Oracle
  2095.  
  2096.  Author:  Tim Bunce
  2097.  Email:   dbi-users@fugue.com
  2098.  
  2099. =item Ingres - DBD::Ingres
  2100.  
  2101.  Author:  Henrik Tougaard
  2102.  Email:   ht@datani.dk,  dbi-users@fugue.com
  2103.  
  2104. =item mSQL - DBD::mSQL
  2105.  
  2106. =item DB2 - DBD::DB2
  2107.  
  2108. =item Empress - DBD::Empress
  2109.  
  2110. =item Informix - DBD::Informix
  2111.  
  2112.  Author:  Jonathan Leffler
  2113.  Email:   johnl@informix.com, dbi-users@fugue.com
  2114.  
  2115. =item Solid - DBD::Solid
  2116.  
  2117.  Author:  Thomas Wenrich
  2118.  Email:   wenrich@site58.ping.at, dbi-users@fugue.com
  2119.  
  2120. =item Postgres - DBD::Pg
  2121.  
  2122.  Author:  Edmund Mergl
  2123.  Email:   mergl@nadia.s.bawue.de, dbi-users@fugue.com
  2124.  
  2125. =item Fulcrum SearchServer - DBD::Fulcrum
  2126.  
  2127.  Author:  Davide Migliavacca
  2128.  Email:   davide.migliavacca@inferentia.it
  2129.  
  2130. =back
  2131.  
  2132. =head1 OTHER RELATED WORK AND PERL MODULES
  2133.  
  2134. =over 4
  2135.  
  2136. =item Apache::DBI by E.Mergl@bawue.de
  2137.  
  2138. To be used with the Apache daemon together with an embedded perl
  2139. interpreter like mod_perl. Establishes a database connection which
  2140. remains open for the lifetime of the http daemon. This way the CGI
  2141. connect and disconnect for every database access becomes superfluous.
  2142.  
  2143. =item JDBC Server by Stuart 'Zen' Bishop <zen@bf.rmit.edu.au>
  2144.  
  2145. The server is written in Perl. The client classes that talk to it are 
  2146. of course in Java. Thus, a Java applet or application will be able to 
  2147. comunicate via the JDBC API with any database that has a DBI driver installed.
  2148. The URL used is in the form jdbc:dbi://host.domain.etc:999/Driver/DBName.
  2149. It seems to be very similar to some commercial products, such as jdbcKona.
  2150.  
  2151. =item Remote Proxy DBD support
  2152.  
  2153.   Carl Declerck <carl@miskatonic.inbe.net>
  2154.   Terry Greenlaw <z50816@mip.mar.lmco.com>
  2155.  
  2156. Carl is developing a generic proxy object module which could form the basis
  2157. of a DBD::Proxy driver in the future. Terry is doing something similar.
  2158.  
  2159. =item SQL Parser - Stephen Zander <stephen.zander@mckesson.com>
  2160.  
  2161. Based on the O'Reilly lex/yacc book examples and byacc.
  2162.  
  2163. =back
  2164.  
  2165. =cut
  2166.